<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item"  type="primary" icon="el-icon-refresh" @click="handleRefresh">
        刷新
      </el-button>
      <el-input v-model="listQuery.searchMsg" placeholder="搜索内容" style="width: 200px;" class="filter-item filter-input"
                @keyup.enter.native="handleFilter"/>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item add" style="margin-left: 10px;" type="primary" icon="el-icon-circle-plus-outline"
                 @click="handleCreate">
        添加
      </el-button>

    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row

    >
      <el-table-column
        type="index"
        label="序号"
        align="center"
        width="50">
      </el-table-column>
      <!-- <el-table-column align="center" label="ID" width="95" >
        <template slot-scope="scope">
          {{ scope.row.Index }}
        </template>
      </el-table-column> -->
      <el-table-column label="用户名" align="center">
        <template slot-scope="scope">
          {{ scope.row.username }}
        </template>
      </el-table-column>
      <el-table-column label="真实姓名" width="180" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="角色" width="180" prop="adminRoles" align="center">
        <template slot-scope="scope">
          {{ scope.row.adminRoles }}


        </template>
      </el-table-column>
      <el-table-column label="状态" width="110" align="center">
        <template slot-scope="scope">
          {{ scope.row.is_login === 0 ? '未激活' : '已激活' }}
        </template>
      </el-table-column>
      <!--<el-table-column class-name="status-col" label="状态" width="110" align="center">-->
      <!--<template slot-scope="scope">-->
      <!--<el-switch-->
      <!--v-model="scope.row.status"-->
      <!--active-color="#13ce66"-->
      <!--@change="handleStatus(scope.row)"-->
      <!--&gt;-->
      <!--</el-switch>-->

      <!--&lt;!&ndash; <el-tag :type="scope.row.status | statusFilter">{{ scope.row.status }}</el-tag> &ndash;&gt;-->
      <!--</template>-->
      <!--</el-table-column>-->
      <el-table-column align="center" prop="created_at" label="创建时间" width="200">
        <template slot-scope="scope">
          <i class="el-icon-time"/>
          <span>{{ scope.row.created_at }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="updated_at" label="更新时间" width="200">
        <template slot-scope="scope">
          <i class="el-icon-time"/>
          <span>{{ scope.row.updated_at }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-if="row.is_login!=1" type="primary" size="mini" @click="activation(row)">
            激&nbsp;&nbsp;&nbsp;活
          </el-button>
          <el-button v-if="row.is_login==1" type="success" size="mini" >
            已激活
          </el-button>

          <el-button size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
                @pagination="fetchData"/>

    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="Form" label-position="left" label-width="90px"
               style="width: 400px; margin-left:50px;">

        <el-form-item label="用户名" prop="username">
          <el-input v-model="Form.username"/>
        </el-form-item>
        <el-form-item label="真实姓名" prop="name">
          <el-input v-model="Form.name"/>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="Form.password" maxlength="16" show-password/>
        </el-form-item>

        <el-form-item label="角色" prop="roleId">
          <el-select v-model="Form.roleId" class="filter-item" placeholder="请选择">
            <el-option v-for="item in roles" :key="item.id" :label="item.name" :value="item.id"/>
          </el-select>
        </el-form-item>

        <el-tabs type="border-card" v-if="dialogStatus!=='create'">

          <el-tab-pane label="信号列表">
            <a-tree
              checkable
              v-model="checkedKeysMenu"
              :show-line="true"
              :defaultExpandAll="true"
              :tree-data="menuList"
              @check="onCheckM"
            >
            </a-tree>
          </el-tab-pane>

        </el-tabs>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import Pagination from '@/components/Pagination' // secondary package based on el-pagination
  import {List, Add, Update, Delete, AdminRolesAll, RolesUpdate, RolesAdd} from '@/api/admin/admin'
  import {MUserSignalsAPI} from '../../../api/meeting/MUserSignals'
  import {MSignalsAPI} from '../../../api/meeting/signals'
  export default {
    filters: {
      statusFilter(status) {
        const statusMap = {
          published: 'success',
          draft: 'gray',
          deleted: 'danger'
        }
        return statusMap[status]
      }
    },
    components: {Pagination},
    name: 'user',
    data() {
      const validatePassword = (rule, value, callback) => {

        if (value.length < 6) {
          callback(new Error('密码长度不能低于6位'))
        } else {
          callback()
        }
      }

      const validateUser = (rule, value, callback) => {
        let reg = /^[a-zA-Z0-9]+$/;
        if (value === '') {
          callback(new Error('用户名不能为空'))
        } else if (!reg.test(value)) {
          callback(new Error('用户名只能输入英文字母及数字'))

        } else {
          callback()
        }
      }
      return {
        list: null,
        listLoading: true,
        total: 0,
        listQuery: {
          page: 1,
          limit: 10,
          searchMsg: ""
        },
        dialogFormVisible: false,
        dialogStatus: "create",
        title: "",
        rules: {
          name: [
            {required: true, message: '请输入账户名', trigger: 'blur'}
          ],
          username: [
            {required: true, validator: validateUser, trigger: 'blur'}
          ],
          password: [
            {required: true, trigger: 'blur', validator: validatePassword}
          ],
          roleId: [
            {required: true, message: '请选择角色', trigger: 'change'}
          ],
        },
        Form: {
          id: null,
          name: "",
          username: "",
          roleId: null,
          password: ""

        },
        roles: null,
        menuList:null,
        checkedKeysMenu:[]
      }
    },
    created() {
      this.fetchData()
    },
    methods: {
      onCheckM(key ,e){
        console.log(key)
        console.log(this.Form)
        console.log(this.checkedKeys)

        console.log(e)


        let data = {
          "uid": this.Form.id,
          "sid": e.node.value
        }
        let flag = false
        let arr = []
        for(let i=0;i<this.menuList.length;i++){
          if(e.node.value == this.menuList[i].value){
            flag = true
            if(e.checked){
              MUserSignalsAPI.add(data).then(response=>{})
            }else{
              MUserSignalsAPI.delete(data).then(response=>{ })
            }
            if(this.menuList[i].children.length>0){

              for(let a =0;a<this.menuList[i].children.length;a++){
                // arr.push(this.parentName[i].children[a].key)
                console.log(this.menuList[i].children)
                if(e.checked){
                  let item = {
                    "uid": this.Form.id,
                    "sid": this.menuList[i].children[a].key
                  }
                  MUserSignalsAPI.add(item).then(response=>{
                  })
                }else{
                  let item = {
                    "uid": this.Form.id,
                    "sid": this.menuList[i].children[a].key
                  }
                  MUserSignalsAPI.delete(item).then(response=>{
                  })
                }
              }
            }
          }
        }
        if(!flag){
          if(e.checked){
            rolesAsMenuAdd(data).then(response=>{})
          }else{
            rolesAsMenuDelete(data).then(response=>{ })
          }
        }
      },
      fetchData() {
        console.log('in to fetchData');
        this.listLoading = true
        List(this.listQuery).then(response => {
          // let list = response.data.list
          // for(let i=0; i<list.length;i++){
          //
          //   if(list[i].adminRoles){
          //     list[i]['adminRolesId'] = list[i].adminRoles.id
          //     list[i].adminRoles = list[i].adminRoles.name
          //   }
          // }
          let list = response.data.list;

          list = list.map(item => {
            if (item.adminRoles) {
              item['adminRolesId'] = item.adminRoles.id;
              item.adminRoles = item.adminRoles.name;
            }
            return item;
          }).filter(item => item.id !== 1); // 过滤掉 adminRolesId 为 1 的项
          const data = list
          this.list = data
          this.total = response.data.queryTotal
          this.listQuery.page = response.data.page
          setTimeout(() => {
            this.listLoading = false
          }, 0.3 * 1000)
        })
        AdminRolesAll().then(response => {
          this.roles = response.data
          this.roles = this.roles.filter(item => item.id !== 1); // 过滤掉 adminRolesId 为 1 的项
        })

        MSignalsAPI.hasAll().then(response=>{
          let data = response.data
          let arr1=[]
          for(let i=0;i<data.length;i++){
            data[i]['label'] = data[i].title
            data[i]['children'] = data[i].childrens
            let a = {
              title: data[i].name,
              value: data[i].id,
              key: data[i].id,
              children:[]
            }
            arr1.push(a)
          }
          this.menuList=arr1
          console.log( this.menuList);
        })
      },
      getList() {
        this.listLoading = true
        List(this.listQuery).then(response => {
          let list = response.data.list
          for (let i = 0; i < list.length; i++) {
            if (list[i].adminRoles) {
              list[i]['adminRolesId'] = list[i].adminRoles.id
              list[i].adminRoles = list[i].adminRoles.name
            }
          }
          const data = list
          this.list = data
          this.total = response.data.queryTotal
          this.listQuery.page = response.data.page
          setTimeout(() => {
            this.listLoading = false
          }, 0.3 * 1000)
        })
      },
      handleFilter() {
        //搜索
        this.listQuery.page = 1
        this.listQuery.searchMsg = this.listQuery.searchMsg.trim()
        this.fetchData()
      },
      handleCreate() {
        //新增
        this.dialogFormVisible = true
        this.title = "添加"
        this.dialogStatus = 'create'
        this.Form = {
          id: null,
          name: "",
          username: "",
          roleId: null,
          password: ""

        }
        setTimeout(() => {
          this.$refs['dataForm'].clearValidate();
        }, 300)
      },
      handleUpdate(row) {
        console.log('in to handleUpdate')
        //编辑
        this.dialogFormVisible = true
        this.title = "修改"
        this.dialogStatus = 'update'
        this.Form = {
          id: row.id,
          name: row.name,
          username: row.username,
          roleId: row.adminRolesId,
          password: row.password,
          is_login: row.is_login
        }
        console.log(row)
        console.log(this.Form)

        MUserSignalsAPI.hasAllByUserId({uid:row.id}).then(response=>{
          this.checkedKeysMenu = []
          console.log(response.data)
          for(let i=0;i<response.data.length;i++){
            this.checkedKeysMenu.push(response.data[i].sid)
          }
        })

      },
      activation(row) {
        //激活
        this.$confirm('确认激活账号？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.Form = {
            id: row.id,
            name: row.name,
            username: row.username,
            roleId: row.adminRolesId,
            password: row.password,
            is_login: 1
          }
          console.log(row)
          console.log(this.Form)
          Update(this.Form).then(() => {
            let data = {
              roleId: this.Form.roleId,
              userId: this.Form.id
            }
            RolesUpdate(data).then(() => {
              this.dialogFormVisible = false
              this.fetchData()
              this.$notify({
                title: 'Success',
                message: '激活成功',
                type: 'success',
                duration: 2000
              })
            })
          })
        }).catch(() => {
        });


      },
      handleDelete(row, index) {
        //删除
        this.$confirm('确认删除？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          Delete({id: row.id}).then(() => {
            this.$notify({
              title: 'Success',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.list.splice(index, 1)
          })
        }).catch(() => {
        });
      },
      handleRefresh() {
        //列表刷新
        this.fetchData()
      },
      handleStatus(row) {
        //更改状态
        console.log(row)
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            Add(this.Form).then((response) => {
              let data = {
                roleId: this.Form.roleId,
                userId: response.data
              }
              RolesAdd(data).then(() => {
                this.dialogFormVisible = false
                this.fetchData()
                this.$notify({
                  title: 'Success',
                  message: '修改成功',
                  type: 'success',
                  duration: 2000
                })
              })
            })
          }
        })
      },
      updateData() {
        console.log('in to updateData');
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            Update(this.Form).then(() => {
              let data = {
                roleId: this.Form.roleId,
                userId: this.Form.id
              }
              RolesUpdate(data).then(() => {
                this.dialogFormVisible = false
                this.fetchData()
                this.$notify({
                  title: 'Success',
                  message: '修改成功',
                  type: 'success',
                  duration: 2000
                })
              })
            })

          }
        })
      }
    }
  }
</script>
<style lang="scss" scoped>
  .filter-container {
    .filter-item {
      margin-bottom: 10px;
    }
    .filter-input {
      margin-left: 20px;
    }
    .add {
      float: right;
    }
  }
</style>
